import { ClearOutlined, DeleteOutlined, RedoOutlined } from '@ant-design/icons';
import { useRequest, useSetState } from 'ahooks';
import { Alert, Button, Form, Input, Modal, Space, Table, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import useScreenSize from '@/hooks/useScreenSize';
import messageBox from '@/utils/messageBox';

import { logoutProxy } from '../../store/userStore';
import { queryDB, resetDB, SqlQuery } from './service';

interface DatabaseType {
  columns: ColumnsType<object>;
  dataSource: object[];
}

const Database = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { isMobile } = useScreenSize();
  const lastSelect = useRef<SqlQuery>({});
  const [buffer, setBuffer] = useSetState<DatabaseType>({
    columns: [],
    dataSource: [],
  });
  const { columns, dataSource } = buffer;
  const [modalApi, modalCtx] = Modal.useModal();

  // 执行SQL查询
  const {
    run: runQuery,
    loading: queryLoading,
    refresh,
  } = useRequest(
    async (params: SqlQuery = form.getFieldsValue()) => {
      await queryDB(params).then(res => {
        const { data } = res;
        // 如果是查询语句则修改表格内容
        if (data instanceof Array) {
          setBuffer({
            columns: Object.keys(data[0]).map((d: any) => ({
              key: d.id,
              title: d,
              dataIndex: d,
            })),
            dataSource: data,
          });
          lastSelect.current = params;
          form.resetFields();
        }
        // 如果不是查询语句则查询查询上一次查询语句
        else {
          runQuery(lastSelect.current);
        }
      });
    },
    { manual: true },
  );

  // 执行数据重置
  const { run: reset, loading: resetLoading } = useRequest(
    async () => {
      modalApi.confirm({
        title: t('warning'),
        content: t('databaseResetConfirm'),
        okType: 'default',
        async onOk() {
          await resetDB().then(() => {
            messageBox.success({ content: t('databaseResetSuccess') });
            setBuffer({ columns: [], dataSource: [] });
          });
          logoutProxy();
          navigate('/auth');
        },
      });
    },
    { manual: true },
  );

  const loading = queryLoading || resetLoading;

  return (
    <Form className="pl-5 pr-5" form={form}>
      <Alert
        showIcon
        className="mt-5 mb-5 animate__animated animate__shakeY"
        message={t('databaseQueryHelp')}
        type="warning"
      />
      <Form.Item name="sql">
        <Space size={isMobile ? 'small' : 'middle'}>
          <Input
            className="w-[15rem] ml-[2px]"
            placeholder={t('databaseQueryPlaceholder') as string}
            onPressEnter={() => runQuery(form.getFieldsValue())}
          />
          <Tooltip title={t('refresh')}>
            <Button
              disabled={Object.keys(lastSelect.current).length === 0}
              loading={loading}
              icon={<RedoOutlined />}
              onClick={refresh}
            />
          </Tooltip>
          <Tooltip title={t('clear')}>
            <Button
              disabled={buffer.dataSource.length === 0}
              loading={loading}
              icon={<DeleteOutlined />}
              onClick={() => setBuffer({ columns: [], dataSource: [] })}
            />
          </Tooltip>
          <Tooltip title={t('reset')}>
            <Button loading={loading} icon={<ClearOutlined />} onClick={reset} />
          </Tooltip>
        </Space>
      </Form.Item>
      <Table
        bordered
        loading={loading}
        pagination={{ position: ['bottomCenter'] }}
        columns={columns}
        dataSource={dataSource}
      />
      {modalCtx}
    </Form>
  );
};

export default Database;
